<template>
  <div class="entry-container">
    <el-card class="entry-card">
      <template #header>
        <div class="card-header">
          <h2>新建日志</h2>
          <div class="tools">
            <el-button type="primary" @click="openDatePicker">选择日期</el-button>
            <span v-if="dateText" class="date-badge">{{ dateText }}（{{ weekdayText }}）</span>
          </div>
        </div>
      </template>

      <el-form label-position="top">
        <el-form-item label="标题">
          <el-input v-model="title" size="large" placeholder="给这篇日志起个标题" />
        </el-form-item>
        <el-form-item label="标签">
          <div class="tag-row">
            <el-select v-model="selectedTagIds" multiple filterable placeholder="选择标签" style="min-width: 260px;">
              <el-option v-for="t in tags" :key="t.id" :label="t.name" :value="t.id" />
            </el-select>
            <el-input v-model="newTagName" placeholder="新标签名称" style="width: 160px;" />
            <el-button @click="addTag" :disabled="!newTagNameTrim">添加</el-button>
          </div>
        </el-form-item>
        <el-form-item label="今日心情（-3 ~ 3）">
          <el-slider v-model="mood" :min="-3" :max="3" :step="1" show-stops :marks="marks" />
        </el-form-item>

        <el-form-item label="内容">
          <el-input
            v-model="content"
            type="textarea"
            :autosize="{ minRows: 8, maxRows: 16 }"
            placeholder="记录今天发生了什么..."
          />
        </el-form-item>

        <div class="actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" :disabled="!selectedDate || !titleTrim" :loading="saving" @click="save">
            保存
          </el-button>
        </div>
      </el-form>
    </el-card>

    <el-dialog v-model="dateDialog" title="选择日期" width="360px" align-center>
      <div class="date-picker-wrap">
        <el-date-picker v-model="datePickValue" type="date" placeholder="选择日期" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dateDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmDate">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createEntry } from '@/api/entries'
import { useTagsStore } from '@/stores/tags'
import { useUserStore } from '@/stores/auth/user'
const router = useRouter()

// UI state
const dateDialog = ref(false)
const datePickValue = ref<Date | null>(new Date())
const selectedDate = ref<Date | null>(new Date())
const title = ref('')
const mood = ref<number>(0)
const content = ref('')
const saving = ref(false)
// tags via store (persisted)
const tagsStore = useTagsStore()
// 直接使用 computed 而不是 storeToRefs，确保响应式
const tags = computed(() => tagsStore.list)
const selectedTagIds = ref<number[]>([])
const newTagName = ref('')

const marks = {
  [-3]: '-3',
  [-2]: '-2',
  [-1]: '-1',
  0: '0',
  1: '1',
  2: '2',
  3: '3',
} as Record<number, string>

function openDatePicker() {
  datePickValue.value = selectedDate.value ?? new Date()
  dateDialog.value = true
}

function confirmDate() {
  selectedDate.value = datePickValue.value ? new Date(datePickValue.value) : null
  dateDialog.value = false
}

const dateText = computed(() => (selectedDate.value ? formatDate(selectedDate.value) : ''))
const weekdayText = computed(() => (selectedDate.value ? getWeekdayText(selectedDate.value) : ''))
const titleTrim = computed(() => title.value.trim().length > 0)
const newTagNameTrim = computed(() => newTagName.value.trim().length > 0)
const userStore = useUserStore()


function formatDate(d: Date) {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

function getWeekdayText(d: Date) {
  const w = d.getDay()
  const names = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return names[w]
}

async function save() {
  if (!selectedDate.value) {
    ElMessage.warning('请选择日期')
    return
  }
  try {
    saving.value = true
    const payload = {
      title: title.value.trim(),
      owner_id: userStore.user?.id,
      date: formatDate(selectedDate.value),
      // weekday: getWeekdayText(selectedDate.value),
      mood: mood.value,
      content: content.value,
      tagIds: selectedTagIds.value,
    }
    const res: any = await createEntry(payload)
    const ok = res && (res.success === true || res.code === 0 || res.code === 200)
    if (!ok) {
      throw new Error(res?.message || '创建失败')
    }
    ElMessage.success('保存成功')
    router.push('/entries')
  } catch (e: any) {
    ElMessage.error(e?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

function goBack() {
  router.back()
}

onMounted(async () => {
  try {
    await tagsStore.fetch()
  } catch (e) {
    console.debug('[tags] load failed', e)
  }
})

async function addTag() {
  const name = newTagName.value.trim()
  if (!name) return
  try {
    const created = await tagsStore.add(name)
    ElMessage.success('添加成功')
    await tagsStore.fetch(true) // 强制刷新标签列表
    // if (created && created.id) {
    //   // 确保新标签被选中，并强制刷新下拉框
    //   if (!selectedTagIds.value.includes(created.id)) {
    //     selectedTagIds.value.push(created.id)
    //   }
      
    //   ElMessage.success(`标签"${created.name}"已添加`)
    // } else {
    //   ElMessage.success('已提交创建（未返回实体）')
    // }
    newTagName.value = ''
  } catch (e: any) {
    console.debug('[tags] create failed', e)
    ElMessage.error(e?.message || '添加标签失败')
  }
}
</script>

<style scoped>
.entry-container {
  display: flex;
  justify-content: center;
  min-height: calc(100vh - 60px);
  background: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%);
  padding: 24px 16px 48px;
}
.entry-card {
  width: 100%;
  max-width: 960px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  border: none;
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-header h2 { margin: 0; color: #5a3e2b; }
.tools { display: flex; align-items: center; gap: 12px; }
.date-badge { color: #6b4f3a; font-size: 14px; }
.actions { display: flex; gap: 12px; justify-content: flex-end; }
.date-picker-wrap { display: flex; justify-content: center; }
.tag-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
</style>